﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;
using System.IO;
using System.Reflection;
using Opalis.QuickIntegrationKit;
using System.Management;

namespace Erlacher.Opalis.Virsto
{
    [OpalisObject("Get Master Service", ShowFilters=false)]
    public class GetMasterService : IOpalisObject 
    {
        //private Settings settings;
        private string s_name = string.Empty;
        private string s_description = string.Empty;
        private int i_size = 0;

        //[OpalisConfiguration]
        //public Settings Settings
        //{
        //    set { settings = value; }
        //    get { return settings; }
        //}

        private string s_server = string.Empty;

        [OpalisInput("Virsto Server")]
        public string Server
        {
            set { s_server = value; }
            get { return ""; }
        }

        private string s_username = string.Empty;

        [OpalisInput("Virsto Server - Username")]
        public string Username
        {
            set { s_username = value; }
            get { return ""; }
        }

        private string s_password = string.Empty;

        [OpalisInput("Virsto Server - Password", PasswordProtected=true)]
        public string Password
        {
            set { s_password = value; }
            get { return ""; }
        }

        public void Design(IOpalisDesigner designer)
        {
            designer.AddOutput("HostName");
            designer.AddOutput("ErrorState");
            designer.AddOutput("ErrorMessage");
            designer.AddOutput("Trace");
           
        }

        public void Execute(IOpalisRequest request, IOpalisResponse response)
        {

            string psscript = "";
            PowerShellHelper.ReturnObject Results;

            ulong size = ulong.Parse(this.i_size.ToString()) * 1024 * 1024 * 1024;

            Assembly _assembly = Assembly.GetExecutingAssembly();
            StreamReader _textStreamReader = new StreamReader(_assembly.GetManifestResourceStream("Erlacher.Opalis.Virsto.PSScripts.GetClusterNode.ps1"));
            psscript = _textStreamReader.ReadToEnd();

            Results = PowerShellHelper.RunScript(psscript, s_username, s_password, s_server);

            string[] felder = Results.Value.Split(new Char[] { '"' });
            string nodename = felder[1];


            Dictionary<string, object> publishedData = new Dictionary<string, object>();
            publishedData.Add("HostName", nodename);
            publishedData.Add("ErrorState", Results.ErrorState.ToString());
            publishedData.Add("ErrorMessage", Results.ErrorMessage );
            publishedData.Add("Trace", Results.Trace );


            response.Publish(publishedData);
            
             
        }
    }
}